package com.example.wanandroid.controller;

import com.example.wanandroid.result.Result;
import com.example.wanandroid.result.ResultUtil;
import com.example.wanandroid.service.UserService;
import com.example.wanandroid.service.ViewService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * @Desc TODO
 * @Date 2020/4/19 12:50
 */
@RestController
public class ViewController {
    @Autowired
    UserService userService;
    @Autowired
    ViewService viewService;


    //查所有人问题 不需要登录
    @GetMapping("/question/getAllQuestions")
    public Result getAllQuestions(Integer page, Integer pageSize) {
        if (page == null) page = 1;
        if (pageSize == null) pageSize = 20;
        PageInfo<HashMap<String, Object>> pageInfo = viewService.getAllQuestions(page, pageSize);
        return ResultUtil.success(pageInfo);
    }

    //查某人问题 不需要登录
    @GetMapping("/question/getQuestionsByUserId")
    public Result getQuestionsByUserId(Long userid, Integer page, Integer pageSize) {
        return getResultByUserid(page, pageSize, userid);
    }

    //查我的问题 需要登录
    @GetMapping("/question/getMyQuestions")
    public Result getMyQuestions(HttpServletRequest request, Integer page, Integer pageSize) {
        Long userid = (Long) request.getAttribute("userid");
        return getResultByUserid(page, pageSize, userid);
    }

    private Result getResultByUserid(Integer page, Integer pageSize, Long userid) {
        if (page == null) page = 1;
        if (pageSize == null) pageSize = 20;
        PageInfo<HashMap<String, Object>> pageInfo = viewService.getQuestionsByUserId(userid, page, pageSize);
        return ResultUtil.success(pageInfo);
    }


    //查我的回答 需要登录
    @GetMapping("/answer/getMyAnswers")
    public Result getMyAnswers(HttpServletRequest request, Integer page, Integer pageSize) {
        Long userid = (Long) request.getAttribute("userid");
        if (page == null) page = 1;
        if (pageSize == null) pageSize = 20;
        PageInfo<HashMap<String, Object>> pageInfo = viewService.getAnswersByUserId(userid, page, pageSize);
        return ResultUtil.success(pageInfo);
    }

    //根据问题id查问题详情和回答列表 不需要登录
    @GetMapping("/question/getQuestionDetails")
    public Result getQuestionDetails(Long questionId, Integer page, Integer pageSize) {
        if (page == null) page = 1;
        if (pageSize == null) pageSize = 20;
        HashMap<String, Object> question = viewService.getQuestionById(questionId);
        HashMap<String, Object> map = new HashMap<>();
        PageInfo<HashMap<String, Object>> pageInfo = viewService.getAnswersByQuestionId(questionId, page, pageSize);
        map.put("question", question);
        map.put("pageInfo", pageInfo);
        return ResultUtil.success(map);
    }

}
